﻿using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using Jinndev.UI;
using UnityEngine.EventSystems;
using System;
using System.IO;

namespace Jinndev {

    /// <summary>
    /// 贴图项
    /// </summary>
    [RequireComponent(typeof(DragHelper))]
    public class TextureItemUI : MonoBehaviour {

        public RawImage rawImage;
        public Text textName;

        private RectTransform imageTransform;
        private DragHelper dragHelper;

        private List<RaycastResult> raycastResults = new List<RaycastResult>();
        private string textureFile;
        private Vector2 originPos;

        private void Awake() {
            imageTransform = rawImage.GetComponent<RectTransform>();

            dragHelper = GetComponent<DragHelper>();
            dragHelper.onStartDrag = OnStartDrag;
            dragHelper.onDrag = OnDrag;
            dragHelper.onEndDrag = OnEndDrag;
        }

        private void Start() {
            imageTransform.sizeDelta = imageTransform.rect.size;
            imageTransform.anchorMin = new Vector2(0.5f, 0.5f);
            imageTransform.anchorMax = new Vector2(0.5f, 0.5f);
        }

        public void Refresh(string textureFile) {
            this.textureFile = textureFile;

            rawImage.texture = MapUtil.LoadTexture(textureFile);
            textName.text = Path.GetFileNameWithoutExtension(textureFile);
        }

        private void OnStartDrag(DragHelper helper, PointerEventData eventData) {
            rawImage.color = new Color(1, 1, 1, 0.75f);
            originPos = imageTransform.anchoredPosition;
            imageTransform.SetParent(UIManager.Instance.canvas.transform, true);
        }

        private void OnDrag(DragHelper helper, PointerEventData eventData, float deltaX, float deltaY) {
            imageTransform.position = Input.mousePosition;
        }

        private void OnEndDrag(DragHelper helper, PointerEventData eventData) {
            rawImage.color = Color.white;
            imageTransform.SetParent(transform, true);
            imageTransform.SetAsFirstSibling();
            imageTransform.anchoredPosition = originPos;

            //(UIManager.Instance.InputModule as StandaloneInputModule)
            raycastResults.Clear();
            EventSystem.current.RaycastAll(eventData, raycastResults);
            if (raycastResults.Count > 0) {
                var gameObject = raycastResults[0].gameObject;
                if (gameObject.name == "LF" || gameObject.name == "RF" || gameObject.name == "LB" || gameObject.name == "RB") {
                    var item = gameObject.transform.parent.GetComponent<TileItemUI>();
                    if (item != null) {
                        item.SetTexture(gameObject.name, textureFile);
                    }
                }
            }
        }

    }

}
